<?php

namespace App\Services\MakeProductOrder;

use App\Models\User;
use App\Models\PayConfig;
use App\Models\UserDivinationRecord;
use Brick\Math\RoundingMode;
use App\Events\OrderCreatedEvent;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Support\Facades\Redis;
use Carbon\Carbon;

class MakeProductOrder
{
	protected ?User $user = null;

	protected ?Model $order = null;

	protected ?GoldRecord $goldRecord = null;

	public function __construct(
		User $user,
		$pay_config_id = 0,
		$record_id=0
		)
	{
		$this->user = $user;
		$this->pay_config_id = $pay_config_id;
		$this->record_id = $record_id;
	}

	protected function create()
	{
		DB::transaction(function () {

			
			$payConfig = PayConfig::find($this->pay_config_id);

			$record = UserDivinationRecord::find($this->record_id);

			$createData = [
				'pay_config_id'=>$this->pay_config_id,
				'total_amount'=>big_decimal($payConfig->price),
				'record_id'=>$this->record_id ?? 0,
			];

			

			$this->order = $this->user->orders()->create($createData);
			
			
			event(new OrderCreatedEvent($this->order));
			$this->order->unsetRelations();
		});

		return $this->order;
	}

	

	public function make()
	{
		return $this->create();
	}
}
